import React, { useState } from 'react';
import { DetailView } from '../core/DetailView';
import { DetailView as DetailViewComponent } from '../components';
import { StringPropertyEditor, NumberPropertyEditor, BooleanPropertyEditor, DatePropertyEditor, DropDownPropertyEditor } from '../components/PropertyEditors';
import { CommonViewController } from '../controllers/CommonViewController';
import './example.less';

/**
 * Example page to demonstrate the DetailView with PropertyEditorComponent
 */
const ExamplePage: React.FC = () => {
  const [savedData, setSavedData] = useState<string | null>(null);

  // Create a detail view model
  const detailView = new DetailView('customerDetail', 'Customer Details');
  
  // Create property editors
  const nameEditor = new StringPropertyEditor('name', 'Customer Name');
  const ageEditor = new NumberPropertyEditor('age', 'Age');
  ageEditor.min = 0;
  ageEditor.max = 120;
  
  const activeEditor = new BooleanPropertyEditor('active', 'Active Customer');
  const birthDateEditor = new DatePropertyEditor('birthDate', 'Birth Date');
  
  const customerTypeEditor = new DropDownPropertyEditor('customerType', 'Customer Type');
  customerTypeEditor.setItems([
    { value: 'individual', text: 'Individual' },
    { value: 'company', text: 'Company' },
    { value: 'government', text: 'Government' }
  ]);
  
  // Add property editors to detail view
  detailView.addPropertyEditor(nameEditor);
  detailView.addPropertyEditor(ageEditor);
  detailView.addPropertyEditor(activeEditor);
  detailView.addPropertyEditor(birthDateEditor);
  detailView.addPropertyEditor(customerTypeEditor);
  
  // Create a sample data object
  const customer = {
    name: 'John Doe',
    age: 35,
    active: true,
    birthDate: '1990-05-15',
    customerType: 'individual'
  };
  
  // Set the object to be displayed
  detailView.setObject(customer);
  
  // Add a common view controller
  const commonController = new CommonViewController();
  
  // Override the save action to show the saved data
  const saveAction = commonController.actions.find(a => a.id === 'Save');
  if (saveAction) {
    saveAction.setExecuteHandler(() => {
      const data = JSON.stringify(detailView.currentObject, null, 2);
      setSavedData(data);
      alert('Customer data saved successfully!');
    });
  }
  
  detailView.addController(commonController);
  
  return (
    <div className="example-page">
      <h1>Mini-XAF Example</h1>
      <p>This example demonstrates a DetailView with various PropertyEditors</p>
      
      <div className="example-container">
        <DetailViewComponent model={detailView} />
      </div>
      
      {savedData && (
        <div className="saved-data">
          <h3>Saved Customer Data:</h3>
          <pre>{savedData}</pre>
        </div>
      )}
    </div>
  );
};

export default ExamplePage;
